package net.maku.framework.common.annotation;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CustomJsonFormatDeserializer extends JsonSerializer<Date> {

    private final String[] patterns;

    public CustomJsonFormatDeserializer(String[] patterns) {
        this.patterns = patterns;
    }

    @Override
    public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        // 选择第一个日期格式
        jsonGenerator.writeString(new SimpleDateFormat(patterns[0]).format(date));
    }
}

class CustomJsonFormatSerializer extends JsonDeserializer<Date> {

    private final String[] patterns;

    public CustomJsonFormatSerializer(String[] patterns) {
        this.patterns = patterns;
    }

    @Override
    public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        String dateAsString = jsonParser.getText();
        for (String pattern : patterns) {
            try {
                return new SimpleDateFormat(pattern).parse(dateAsString);
            } catch (ParseException e) {
                // 如果解析失败，尝试下一个格式
            }
        }
        throw new IOException("Unparseable date: " + dateAsString);
    }
}
